package com.iwhale.zcm.utils;

import ch.qos.logback.classic.gaffer.PropertyUtil;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {
    public static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(PropertiesUtil.class);
    private static Properties props;

    static {
        loadProps();
    }

    private synchronized static void loadProps() {
        LOGGER.info("开始加载properties文件内容... ...");
        props = new Properties();
        InputStream in = null;
        try {
            in = PropertiesUtil.class.getResourceAsStream("/nginxlogfile.properties");
            props.load(in);
        } catch (FileNotFoundException e) {
            LOGGER.error("config.properties文件未找到");
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                LOGGER.error("config.properties文件流关闭出现异常");
            }
        }
        LOGGER.info("加载properties文件内容完成...........");
        LOGGER.info("properties文件内容：" + props);
    }

    /**
     * 根据配置文件key获取配置参数值
     *
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

    public static Object setProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.setProperty(key, defaultValue);
    }

    public static void setProperty(Map<String, String> data) {
        try {
            InputStream is = PropertiesUtil.class.getResourceAsStream("/nginxlogfile.properties");
            props.load(is);
            if (data != null) {
                Iterator<Map.Entry<String, String>> iter = data.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    props.setProperty(entry.getKey().toString(), entry.getValue().toString());
                }
            }
            OutputStream out = new FileOutputStream("nginxlogfile.properties");
            props.store(out, null);
            is.close();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}
